import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot} from '@angular/router';
import {GnLoginUser} from './LoginUser';
import {GnSiteInfo} from './SiteInfo';
import {GnMessageService} from './MessageService';

@Injectable()
export class GnRouteGuard implements CanActivate {

  constructor(private user: GnLoginUser,
              private siteInfo: GnSiteInfo,
              private router: Router,
              private messageService: GnMessageService) {
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (!this.user.isLogin) {
      sessionStorage.setItem('blockUrl', state.url);
      this.messageService.warn('请登录');
      this.router.navigateByUrl(this.siteInfo.loginUrl);
      return false;
    } else {
      const authority = this.siteInfo.siteAuthorities?.find((item) => item.url === state.url);
      if (!authority || this.user.authorities.includes(authority.authority)) {
        return true;
      } else {
        sessionStorage.setItem('blockUrl', state.url);
        this.messageService.warn('您的权限不足');
        this.router.navigateByUrl(this.siteInfo.loginUrl);
        return false;
      }
    }
  }
}
